// challenge-game.js - 闯关游戏页面功能

// 游戏配置
const gameConfig = {
    viewportSize: 600,      // 可视区域大小
    worldSize: 1200,        // 世界大小
    gridSize: 20,           // 网格大小
    gridCountX: 60,         // 网格数量X（默认：1200/20=60）
    gridCountY: 60,         // 网格数量Y（默认：1200/20=60）
    initialSpeed: 150,      // 初始速度（毫秒）
    maxSpeed: 50,           // 最大速度
    speedIncrement: 10,     // 每关速度增量
    boundaryWarningDistance: 3, // 边界警告距离（网格数）
    foodTypes: {            // 食物类型配置
        normal: {
            score: 10,
            length: 1,
            color: '#ff6b6b',
            spawnChance: 0.7
        },
        highScore: {
            score: 30,
            length: 3,
            color: '#feca57',
            spawnChance: 0.3
        }
    },
    obstacleConfig: {       // 障碍物配置
        spawnChance: 0.2,   // 障碍物生成几率
        maxObstacles: 5     // 最大障碍物数量
    }
};

// 游戏状态
let gameState = {
    isRunning: false,
    score: 0,
    level: 1,
    snakeLength: 3,        // 蛇的长度（替代生命值）
    time: 0,
    snake: [],
    food: { x: 0, y: 0 },
    direction: 'right',
    nextDirection: 'right',
    gameLoop: null,
    difficulty: 'medium',
    camera: { x: 0, y: 0 },  // 摄像机位置
    deathEffect: {           // 死亡特效
        active: false,
        duration: 1000,      // 特效持续时间（毫秒）
        startTime: 0,
        particles: []       // 粒子效果
    },
    inputBuffer: [],         // 输入缓冲队列
    boundaryWarning: {       // 边界警告状态
        active: false,
        direction: '',       // 警告方向：'left', 'right', 'top', 'bottom'
        intensity: 0         // 警告强度 0-1
    },
    miniMap: {               // 小地图状态
        width: 120,          // 小地图宽度
        height: 120,         // 小地图高度
        margin: 10           // 小地图边距
    },
    obstacles: [],           // 障碍物数组
    currentFoodType: 'normal', // 当前食物类型
    levelComplete: false,    // 关卡完成状态
    currentMap: null,        // 当前加载的地图数据
    debugMode: false         // 调试模式
};

// 网格缓存Canvas
let gridCanvas = null;

// DOM元素
let domElements = {};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeGame();
    setupEventListeners();
    
    // 初始化网格缓存
    initGridCache();
    
    // 检查URL参数，如果有地图文件参数则加载地图
    const urlParams = new URLSearchParams(window.location.search);
    const mapFile = urlParams.get('map');
    if (mapFile) {
        loadMap(mapFile);
    }
});

// 初始化网格缓存
function initGridCache() {
    const worldSize = gameConfig.worldSize;
    const gridSize = gameConfig.gridSize;
    
    // 创建离屏Canvas
    gridCanvas = document.createElement('canvas');
    gridCanvas.width = worldSize;
    gridCanvas.height = worldSize;
    const ctx = gridCanvas.getContext('2d');
    
    // 绘制网格到缓存
    ctx.fillStyle = '#000';
    ctx.fillRect(0, 0, worldSize, worldSize);
    
    // 绘制网格线
    ctx.strokeStyle = '#444';
    ctx.lineWidth = 1.5;
    for (let i = 0; i <= worldSize; i += gridSize) {
        ctx.beginPath();
        ctx.moveTo(i, 0);
        ctx.lineTo(i, worldSize);
        ctx.stroke();
        ctx.beginPath();
        ctx.moveTo(0, i);
        ctx.lineTo(worldSize, i);
        ctx.stroke();
    }
    
    // 注意：不在网格缓存中绘制大地图边界，边界将在drawGame中单独绘制
}

// 初始化游戏
function initializeGame() {
    // 获取DOM元素
    domElements = {
        canvas: document.getElementById('gameCanvas'),
        scoreValue: document.getElementById('scoreValue'),
        levelValue: document.getElementById('levelValue'),
        snakeLengthValue: document.getElementById('snakeLengthValue'),
        timeValue: document.getElementById('timeValue'),
        levelProgress: document.getElementById('levelProgress'),
        progressFill: document.getElementById('progressFill'),
        targetScore: document.getElementById('targetScore'),
        startBtn: document.getElementById('startBtn'),
        pauseBtn: document.getElementById('pauseBtn'),
        resetBtn: document.getElementById('resetBtn'),
        gameOverlay: document.getElementById('gameOverlay'),
        overlayTitle: document.getElementById('overlayTitle'),
        overlayMessage: document.getElementById('overlayMessage'),
        restartBtn: document.getElementById('restartBtn'),
        menuBtn: document.getElementById('menuBtn'),
        menuBtnOverlay: document.getElementById('menuBtnOverlay'),
        mobileUp: document.getElementById('mobileUp'),
        mobileDown: document.getElementById('mobileDown'),
        mobileLeft: document.getElementById('mobileLeft'),
        mobileRight: document.getElementById('mobileRight')
    };
    
    // 设置画布尺寸
    domElements.canvas.width = gameConfig.viewportSize;
    domElements.canvas.height = gameConfig.viewportSize;
    
    // 获取画布上下文
    const ctx = domElements.canvas.getContext('2d');
    
    // 初始化障碍物渲染器
    if (window.obstacleRenderer && typeof window.obstacleRenderer.initialize === 'function') {
        window.obstacleRenderer.initialize(ctx, gameConfig);
        console.log('障碍物渲染器初始化完成');
    } else {
        console.warn('障碍物渲染器未找到或初始化函数不存在');
    }
    
    // 初始化摄像机位置
    gameState.camera = { x: 0, y: 0 };
    
    // 获取难度设置
    gameState.difficulty = localStorage.getItem('selectedDifficulty') || 'medium';
    
    // 根据难度调整游戏参数
    adjustDifficulty();
    
    // 初始化游戏
    resetGame();
    
    // 显示开始界面
    showOverlay('贪吃蛇闯关模式', '选择难度后点击开始游戏');
}

// 根据难度调整游戏参数
function adjustDifficulty() {
    switch(gameState.difficulty) {
        case 'easy':
            gameState.snakeLength = 5;
            gameConfig.initialSpeed = 200;
            gameConfig.speedIncrement = 3;
            break;
        case 'medium':
            gameState.snakeLength = 3;
            gameConfig.initialSpeed = 150;
            gameConfig.speedIncrement = 5;
            break;
        case 'hard':
            gameState.snakeLength = 1;
            gameConfig.initialSpeed = 100;
            gameConfig.speedIncrement = 8;
            break;
    }
}

// 设置事件监听器
function setupEventListeners() {
    // 键盘控制
    document.addEventListener('keydown', handleKeyPress);
    
    // 按钮事件
    domElements.startBtn.addEventListener('click', startGame);
    domElements.pauseBtn.addEventListener('click', togglePause);
    domElements.resetBtn.addEventListener('click', resetGame);
    domElements.restartBtn.addEventListener('click', restartGame);
    domElements.menuBtn.addEventListener('click', goToMenu);
    
    // 移动端控制
    if (domElements.mobileUp) {
        domElements.mobileUp.addEventListener('click', () => changeDirection('up'));
        domElements.mobileDown.addEventListener('click', () => changeDirection('down'));
        domElements.mobileLeft.addEventListener('click', () => changeDirection('left'));
        domElements.mobileRight.addEventListener('click', () => changeDirection('right'));
    }
    
    // 覆盖层按钮事件
    domElements.menuBtnOverlay.addEventListener('click', goToMenu);
}

// 处理键盘按键
function handleKeyPress(e) {
    // 防止重复按键
    if (e.repeat) return;
    
    // 检查是否在关卡完成状态
    if (gameState.levelComplete) {
        // 关卡完成状态下，空格键进入下一关
        if (e.key === ' ') {
            e.preventDefault();
            goToNextLevel();
            return;
        }
        // 关卡完成状态下，P键无效
        if (e.key === 'p' || e.key === 'P') {
            e.preventDefault();
            return;
        }
    }
    
    // 游戏未运行时的按键处理
    if (!gameState.isRunning) {
        // 空格键开始游戏
        if (e.key === ' ') {
            e.preventDefault();
            startGame();
            return;
        }
        // P键无效
        if (e.key === 'p' || e.key === 'P') {
            e.preventDefault();
            return;
        }
        return;
    }
    
    // 游戏运行时的按键处理
    let direction = null;
    
    switch(e.key) {
        case 'ArrowUp':
        case 'w':
        case 'W':
            direction = 'up';
            break;
        case 'ArrowDown':
        case 's':
        case 'S':
            direction = 'down';
            break;
        case 'ArrowLeft':
        case 'a':
        case 'A':
            direction = 'left';
            break;
        case 'ArrowRight':
        case 'd':
        case 'D':
            direction = 'right';
            break;
        case ' ':
            // 空格键暂停/继续
            e.preventDefault();
            togglePause();
            return;
        case 'p':
        case 'P':
            // P键暂停/继续
            e.preventDefault();
            togglePause();
            return;
        case 'Escape':
            goToMenu();
            return;
    }
    
    if (direction) {
        // 将输入添加到缓冲队列（最多保留2个输入）
        if (gameState.inputBuffer.length < 2) {
            gameState.inputBuffer.push(direction);
        }
    }
}

// 改变方向
function changeDirection(newDirection) {
    // 防止直接反向移动
    if ((gameState.direction === 'up' && newDirection === 'down') ||
        (gameState.direction === 'down' && newDirection === 'up') ||
        (gameState.direction === 'left' && newDirection === 'right') ||
        (gameState.direction === 'right' && newDirection === 'left')) {
        return;
    }
    
    gameState.nextDirection = newDirection;
}

// 处理输入缓冲
function processInputBuffer() {
    // 如果缓冲队列中有输入，处理第一个输入
    if (gameState.inputBuffer.length > 0) {
        const nextDirection = gameState.inputBuffer.shift(); // 取出队列中的第一个输入
        changeDirection(nextDirection);
    }
}

// 开始游戏
function startGame() {
    if (gameState.isRunning) return;
    
    gameState.isRunning = true;
    domElements.startBtn.textContent = '重新开始';
    hideOverlay();
    
    // 开始游戏循环
    gameState.gameLoop = setInterval(gameUpdate, gameConfig.initialSpeed);
    
    // 开始计时器
    startTimer();
}

// 切换暂停状态
function togglePause() {
    if (!gameState.isRunning) return;
    
    if (gameState.gameLoop) {
        clearInterval(gameState.gameLoop);
        gameState.gameLoop = null;
        domElements.pauseBtn.textContent = '继续';
        showOverlay('游戏暂停', '点击继续或按空格键继续游戏');
    } else {
        gameState.gameLoop = setInterval(gameUpdate, getCurrentSpeed());
        domElements.pauseBtn.textContent = '暂停';
        hideOverlay();
    }
}

// 重置游戏
function resetGame() {
    // 清除游戏循环
    if (gameState.gameLoop) {
        clearInterval(gameState.gameLoop);
        gameState.gameLoop = null;
    }
    
    // 重置游戏状态
    gameState.score = 0;
    gameState.level = 1;
    gameState.time = 0;
    gameState.isRunning = false;
    gameState.direction = 'right';
    gameState.nextDirection = 'right';
    gameState.inputBuffer = [];  // 清空输入缓冲
    
    // 根据难度重置生命值
    adjustDifficulty();
    
    // 初始化蛇
    initializeSnake();
    
    // 生成食物
    generateFood();
    
    // 只有在没有加载地图时才生成随机障碍物
    if (!gameState.currentMap) {
        generateObstacles();
    }
    
    // 更新UI
    updateUI();
    
    // 重置按钮文本
    domElements.startBtn.textContent = '开始游戏';
    domElements.pauseBtn.textContent = '暂停';
    
    // 绘制初始状态
    drawGame();
}

// 重新开始游戏
function restartGame() {
    resetGame();
    startGame();
}

// 返回菜单
function goToMenu() {
    window.location.href = 'choose.html';
}

// 初始化蛇
function initializeSnake() {
    gameState.snake = [];
    
    // 根据当前蛇的长度初始化蛇
    for (let i = 0; i < gameState.snakeLength; i++) {
        gameState.snake.push({ x: 5 - i, y: 10 });
    }
}

// 重置蛇（死亡后重新开始）
function resetSnake() {
    // 重新初始化蛇
    initializeSnake();
    
    // 更新UI显示
    updateUI();
    
    // 重新绘制游戏
    drawGame();
}

// 生成食物
function generateFood() {
    const maxPosition = gameConfig.worldSize / gameConfig.gridSize - 1;
    
    // 随机选择食物类型
    const foodTypes = Object.keys(gameConfig.foodTypes);
    const randomValue = Math.random();
    let cumulativeChance = 0;
    
    for (const type of foodTypes) {
        cumulativeChance += gameConfig.foodTypes[type].spawnChance;
        if (randomValue <= cumulativeChance) {
            gameState.currentFoodType = type;
            break;
        }
    }
    
    // 确保食物不会生成在蛇身上或障碍物上
    let foodPosition;
    do {
        foodPosition = {
            x: Math.floor(Math.random() * maxPosition),
            y: Math.floor(Math.random() * maxPosition)
        };
    } while (isPositionOnSnake(foodPosition.x, foodPosition.y) || 
             isPositionOccupied(foodPosition, gameState.obstacles));
    
    gameState.food = foodPosition;
}

// 检查位置是否在蛇身上
function isPositionOnSnake(x, y) {
    return gameState.snake.some(segment => segment.x === x && segment.y === y);
}

// 检查位置是否被占用（蛇身或障碍物）
function isPositionOccupied(position, array) {
    return array.some(item => item.x === position.x && item.y === position.y);
}

// 生成障碍物
function generateObstacles() {
    gameState.obstacles = [];
    
    // 在默认地图中间添加一个固定的3x3障碍物
    const centerX = Math.floor((gameConfig.worldSize / gameConfig.gridSize) / 2);
    const centerY = Math.floor((gameConfig.worldSize / gameConfig.gridSize) / 2);
    
    // 创建3x3的障碍物
    for (let dx = -1; dx <= 1; dx++) {
        for (let dy = -1; dy <= 1; dy++) {
            const obstacle = {
                x: centerX + dx,
                y: centerY + dy
            };
            
            // 检查位置是否有效（不在蛇身上，不与食物重叠）
            if (!isPositionOnSnake(obstacle.x, obstacle.y) && 
                !(gameState.food && obstacle.x === gameState.food.x && obstacle.y === gameState.food.y)) {
                gameState.obstacles.push(obstacle);
            }
        }
    }
    
    console.log('默认地图：在中间位置添加了3x3障碍物，坐标范围：', 
        `x:${centerX-1}-${centerX+1}, y:${centerY-1}-${centerY+1}`);
    console.log('障碍物数量：', gameState.obstacles.length);
    
    // 原有的随机障碍物生成逻辑（保留但降低几率）
    const maxObstacles = gameConfig.obstacleConfig.maxObstacles;
    const spawnChance = gameConfig.obstacleConfig.spawnChance * 0.1; // 降低随机障碍物生成几率
    
    // 根据生成几率决定是否生成额外障碍物
    if (Math.random() > spawnChance) return;
    
    const numObstacles = Math.floor(Math.random() * maxObstacles) + 1;
    
    for (let i = 0; i < numObstacles; i++) {
        let obstacle;
        let attempts = 0;
        
        do {
            obstacle = {
                x: Math.floor(Math.random() * (gameConfig.worldSize / gameConfig.gridSize)),
                y: Math.floor(Math.random() * (gameConfig.worldSize / gameConfig.gridSize))
            };
            attempts++;
        } while (
            (isPositionOnSnake(obstacle.x, obstacle.y) || 
             isPositionOccupied(obstacle, gameState.obstacles) ||
             (gameState.food && obstacle.x === gameState.food.x && obstacle.y === gameState.food.y)) &&
            attempts < 100
        );
        
        if (attempts < 100) {
            gameState.obstacles.push(obstacle);
        }
    }
}

// 游戏更新循环
function gameUpdate() {
    // 处理输入缓冲
    processInputBuffer();
    
    // 更新方向
    gameState.direction = gameState.nextDirection;
    
    // 移动蛇
    moveSnake();
    
    // 更新摄像机位置（跟随蛇头）
    updateCamera();
    
    // 检查边界接近警告
    checkBoundaryWarning();
    
    // 检查碰撞
    if (checkCollisions()) {
        gameOver();
        return;
    }
    
    // 检查是否吃到食物
    if (checkFoodCollision()) {
        handleFoodEaten();
    }
    
    // 绘制游戏
    drawGame();
    
    // 更新UI
    updateUI();
}

// 移动蛇
function moveSnake() {
    const head = { ...gameState.snake[0] };
    
    // 根据方向移动头部
    switch(gameState.direction) {
        case 'up':
            head.y -= 1;
            break;
        case 'down':
            head.y += 1;
            break;
        case 'left':
            head.x -= 1;
            break;
        case 'right':
            head.x += 1;
            break;
    }
    
    // 添加新的头部
    gameState.snake.unshift(head);
    
    // 如果没有吃到食物，移除尾部
    if (!checkFoodCollision()) {
        gameState.snake.pop();
    } else {
        // 如果吃到食物，蛇的长度增加，不需要移除尾部
        // 只有在蛇的实际长度超过设定的长度时才移除尾部
        while (gameState.snake.length > gameState.snakeLength) {
            gameState.snake.pop();
        }
    }
}

// 检查碰撞
function checkCollisions() {
    const head = gameState.snake[0];
    const maxPosition = gameConfig.worldSize / gameConfig.gridSize - 1;
    
    // 检查墙壁碰撞
    if (head.x < 0 || head.x > maxPosition || head.y < 0 || head.y > maxPosition) {
        // 撞墙时蛇长度减半（最小为1）
        gameState.snakeLength = Math.max(1, Math.floor(gameState.snakeLength / 2));
        if (gameState.snakeLength <= 1) {
            return true; // 游戏结束
        } else {
            triggerDeathEffect();
            resetSnake();
            return false; // 继续游戏
        }
    }
    
    // 检查自身碰撞（跳过头部）
    for (let i = 1; i < gameState.snake.length; i++) {
        if (head.x === gameState.snake[i].x && head.y === gameState.snake[i].y) {
            // 撞到自己时蛇长度减半（最小为1）
            gameState.snakeLength = Math.max(1, Math.floor(gameState.snakeLength / 2));
            if (gameState.snakeLength <= 1) {
                return true; // 游戏结束
            } else {
                triggerDeathEffect();
                resetSnake();
                return false; // 继续游戏
            }
        }
    }
    
    // 检查障碍物碰撞
    const collidingObstacle = gameState.obstacles.find(obstacle => head.x === obstacle.x && head.y === obstacle.y);
    if (collidingObstacle) {
        console.log('🐍 撞到障碍物！位置:', head.x, head.y);
        console.log('障碍物列表:', gameState.obstacles);
        console.log('碰撞的障碍物:', collidingObstacle);
        console.log('蛇头位置:', head);
        console.log('障碍物数量:', gameState.obstacles.length);
        
        // 在调试模式下，显示详细的碰撞信息
        if (gameState.debugMode) {
            console.log('=== 碰撞检测调试信息 ===');
            console.log('蛇头坐标:', head.x, head.y);
            console.log('障碍物坐标:', collidingObstacle.x, collidingObstacle.y);
            console.log('坐标是否相等:', head.x === collidingObstacle.x && head.y === collidingObstacle.y);
            console.log('障碍物数组长度:', gameState.obstacles.length);
            console.log('障碍物数组内容:');
            gameState.obstacles.forEach((obs, idx) => {
                console.log(`  [${idx}] x=${obs.x}, y=${obs.y}`);
            });
        }
        
        // 撞到障碍物时蛇长度减半（最小为1）
        gameState.snakeLength = Math.max(1, Math.floor(gameState.snakeLength / 2));
        if (gameState.snakeLength <= 1) {
            return true; // 游戏结束
        } else {
            triggerDeathEffect();
            resetSnake();
            return false; // 继续游戏
        }
    }
    
    return false;
}

// 检查食物碰撞
function checkFoodCollision() {
    const head = gameState.snake[0];
    return head.x === gameState.food.x && head.y === gameState.food.y;
}

// 检查边界接近警告
function checkBoundaryWarning() {
    const head = gameState.snake[0];
    const maxPosition = gameConfig.worldSize / gameConfig.gridSize - 1;
    const warningDistance = gameConfig.boundaryWarningDistance;
    
    // 重置警告状态
    gameState.boundaryWarning.active = false;
    gameState.boundaryWarning.direction = '';
    gameState.boundaryWarning.intensity = 0;
    
    // 检查各个方向的边界距离
    const distances = {
        left: head.x,
        right: maxPosition - head.x,
        top: head.y,
        bottom: maxPosition - head.y
    };
    
    // 找到最小距离
    const minDistance = Math.min(...Object.values(distances));
    
    // 如果距离小于警告距离，触发警告
    if (minDistance <= warningDistance) {
        gameState.boundaryWarning.active = true;
        
        // 确定警告方向
        for (const [direction, distance] of Object.entries(distances)) {
            if (distance === minDistance) {
                gameState.boundaryWarning.direction = direction;
                break;
            }
        }
        
        // 计算警告强度（距离越近强度越大）
        gameState.boundaryWarning.intensity = 1 - (minDistance / warningDistance);
    }
}

// 更新摄像机位置（跟随蛇头）
function updateCamera() {
    if (gameState.snake.length === 0) return;
    
    const head = gameState.snake[0];
    const gridSize = gameConfig.gridSize;
    const viewportSize = gameConfig.viewportSize;
    const worldSize = gameConfig.worldSize;
    
    // 计算蛇头在像素坐标中的位置
    const headPixelX = head.x * gridSize;
    const headPixelY = head.y * gridSize;
    
    // 计算摄像机应该跟随的位置（使蛇头位于可视区域中心）
    const targetCameraX = headPixelX - viewportSize / 2;
    const targetCameraY = headPixelY - viewportSize / 2;
    
    // 直接设置摄像机位置，不进行平滑插值
    gameState.camera.x = targetCameraX;
    gameState.camera.y = targetCameraY;
    
    // 限制摄像机位置不超过世界边界
    gameState.camera.x = Math.max(0, Math.min(gameState.camera.x, worldSize - viewportSize));
    gameState.camera.y = Math.max(0, Math.min(gameState.camera.y, worldSize - viewportSize));
}

// 处理吃到食物
function handleFoodEaten() {
    // 根据食物类型增加分数和长度
    const foodType = gameConfig.foodTypes[gameState.currentFoodType];
    gameState.score += foodType.score * gameState.level;
    gameState.snakeLength += foodType.length;
    
    // 检查升级
    if (gameState.score >= gameState.level * 100) {
        // 关卡完成，自动暂停
        completeLevel();
    }
    
    // 生成新食物
    generateFood();
}

// 关卡完成处理
function completeLevel() {
    // 自动暂停游戏
    if (gameState.gameLoop) {
        clearInterval(gameState.gameLoop);
        gameState.gameLoop = null;
    }
    
    // 显示关卡完成弹窗
    showLevelCompletePopup();
}

// 显示关卡完成弹窗
function showLevelCompletePopup() {
    // 设置关卡完成状态
    gameState.levelComplete = true;
    
    // 显示覆盖层
    showOverlay(`关卡 ${gameState.level} 完成`, `恭喜！您已完成第${gameState.level}关\n准备进入第${gameState.level + 1}关`);
    
    // 清空现有按钮，添加下一关按钮
    const overlayContent = document.querySelector('.overlay-content');
    const existingButtons = overlayContent.querySelectorAll('.overlay-buttons');
    existingButtons.forEach(btn => btn.remove());
    
    // 创建下一关按钮
    const buttonsDiv = document.createElement('div');
    buttonsDiv.className = 'overlay-buttons';
    
    const nextLevelBtn = document.createElement('button');
    nextLevelBtn.id = 'nextLevelBtn';
    nextLevelBtn.className = 'btn-overlay btn-overlay-success';
    nextLevelBtn.innerHTML = '<i class="bi bi-arrow-right me-2"></i>进入下一关';
    nextLevelBtn.onclick = function() {
        goToNextLevel();
    };
    
    const restartBtn = document.createElement('button');
    restartBtn.id = 'restartBtn';
    restartBtn.className = 'btn-overlay';
    restartBtn.innerHTML = '<i class="bi bi-arrow-repeat me-2"></i>重新开始';
    restartBtn.onclick = function() {
        resetGame();
        hideOverlay();
    };
    
    const menuBtn = document.createElement('button');
    menuBtn.id = 'menuBtnOverlay';
    menuBtn.className = 'btn-overlay btn-overlay-danger';
    menuBtn.innerHTML = '<i class="bi bi-house me-2"></i>返回主页';
    menuBtn.onclick = goToMenu;
    
    buttonsDiv.appendChild(nextLevelBtn);
    buttonsDiv.appendChild(restartBtn);
    buttonsDiv.appendChild(menuBtn);
    
    overlayContent.appendChild(buttonsDiv);
    
    // 更新统计信息
    document.getElementById('finalScore').textContent = gameState.score;
    document.getElementById('finalLevel').textContent = gameState.level;
}

// 进入下一关
function goToNextLevel() {
    // 清除关卡完成状态
    gameState.levelComplete = false;
    
    // 进入下一关
    gameState.level++;
    
    // 重置蛇的位置和状态
    resetSnake();
    
    // 生成新食物
    generateFood();
    
    // 生成新障碍物
    generateObstacles();
    
    // 更新UI显示新关卡
    updateUI();
    
    // 隐藏覆盖层
    hideOverlay();
    
    // 重新开始游戏循环
    gameState.gameLoop = setInterval(gameUpdate, getCurrentSpeed());
}

// 获取当前速度
function getCurrentSpeed() {
    return Math.max(gameConfig.maxSpeed, gameConfig.initialSpeed - (gameState.level - 1) * gameConfig.speedIncrement);
}

// 绘制游戏
function drawGame() {
    const ctx = domElements.canvas.getContext('2d');
    const gridSize = gameConfig.gridSize;
    const worldSize = gameConfig.worldSize;
    const viewportSize = gameConfig.viewportSize;
    
    // 清空画布
    ctx.fillStyle = '#000';
    ctx.fillRect(0, 0, viewportSize, viewportSize);
    
    // 保存当前画布状态
    ctx.save();
    
    // 应用摄像机变换（移动画布使蛇头位于可视区域中心）
    ctx.translate(-gameState.camera.x, -gameState.camera.y);
    
    // 直接绘制网格背景
    ctx.strokeStyle = '#444';
    ctx.lineWidth = 1.5;
    for (let i = 0; i <= worldSize; i += gridSize) {
        ctx.beginPath();
        ctx.moveTo(i, 0);
        ctx.lineTo(i, worldSize);
        ctx.stroke();
        ctx.beginPath();
        ctx.moveTo(0, i);
        ctx.lineTo(worldSize, i);
        ctx.stroke();
    }
    
    // 绘制大地图边界
    ctx.strokeStyle = '#ff0000';
    ctx.lineWidth = 3;
    
    // 绘制整个世界的边界
    ctx.beginPath();
    ctx.rect(0, 0, worldSize, worldSize);
    ctx.stroke();
    
    // 绘制食物
    const foodType = gameConfig.foodTypes[gameState.currentFoodType];
    ctx.fillStyle = foodType.color;
    ctx.fillRect(gameState.food.x * gridSize, gameState.food.y * gridSize, gridSize, gridSize);
    
    // 如果是高分食物，添加特殊效果
    if (gameState.currentFoodType === 'highScore') {
        ctx.strokeStyle = '#ffffff';
        ctx.lineWidth = 2;
        ctx.strokeRect(gameState.food.x * gridSize, gameState.food.y * gridSize, gridSize, gridSize);
    }
    
    // 绘制障碍物 - 使用障碍物渲染器
    if (window.obstacleRenderer && typeof window.obstacleRenderer.render === 'function') {
        console.log('使用障碍物渲染器渲染障碍物...');
        console.log('障碍物渲染器状态:', {
            initialized: window.obstacleRenderer.initialized,
            obstacleCount: window.obstacleRenderer.getObstacleCount ? window.obstacleRenderer.getObstacleCount() : 'N/A'
        });
        // 计算正确的缩放比例
        const scaleX = gridSize;
        const scaleY = gridSize;
        // 传递摄像机偏移参数
        window.obstacleRenderer.render(ctx, scaleX, scaleY, gameState.camera);
    } else {
        console.log('使用备用渲染方式渲染障碍物...');
        console.log('障碍物数量:', gameState.obstacles.length);
        // 备用渲染方式
        ctx.fillStyle = '#808080'; // 灰色障碍物
        gameState.obstacles.forEach(obstacle => {
            const screenX = obstacle.x * gridSize - gameState.camera.x;
            const screenY = obstacle.y * gridSize - gameState.camera.y;
            
            if (screenX >= -gridSize && screenX <= gameConfig.viewportSize && 
                screenY >= -gridSize && screenY <= gameConfig.viewportSize) {
                ctx.fillRect(screenX, screenY, gridSize, gridSize);
                ctx.strokeStyle = '#606060';
                ctx.lineWidth = 2;
                ctx.strokeRect(screenX, screenY, gridSize, gridSize);
            }
        });
    }
    
    // 绘制蛇
    gameState.snake.forEach((segment, index) => {
        if (index === 0) {
            // 蛇头
            ctx.fillStyle = '#4CAF50';
        } else {
            // 蛇身
            const gradient = index / gameState.snake.length;
            ctx.fillStyle = `rgb(${76 + gradient * 50}, ${175 - gradient * 50}, ${80})`;
        }
        ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize, gridSize);
        
        // 边框
        ctx.strokeStyle = '#333';
        ctx.lineWidth = 1;
        ctx.strokeRect(segment.x * gridSize, segment.y * gridSize, gridSize, gridSize);
    });
    
    // 恢复画布状态
    ctx.restore();
    
    // 绘制死亡特效粒子
    if (gameState.deathEffect.active) {
        gameState.deathEffect.particles.forEach(particle => {
            ctx.save();
            ctx.globalAlpha = particle.life;
            ctx.fillStyle = particle.color;
            ctx.beginPath();
            ctx.arc(particle.x, particle.y, 3 * particle.life, 0, Math.PI * 2);
            ctx.fill();
            ctx.restore();
        });
    }
    
    // 绘制可视区域边界（绿色边框）
    ctx.strokeStyle = '#4CAF50';
    ctx.lineWidth = 2;
    ctx.strokeRect(0, 0, viewportSize, viewportSize);
    
    // 绘制边界警告
    drawBoundaryWarning(ctx);
    
    // 绘制小地图
    drawMiniMap();
    
    // 调试：绘制障碍物位置标记
    drawObstacleDebugMarkers(ctx);
    
    // 调试：绘制障碍物碰撞标记
    if (gameState.debugMode) {
        drawObstacleCollisionMarkers(ctx);
    }
}

// 绘制障碍物调试标记
function drawObstacleDebugMarkers(ctx) {
    const gridSize = gameConfig.gridSize;
    
    // 只在调试模式下显示
    if (!gameState.debugMode) return;
    
    ctx.fillStyle = '#ff0000';
    ctx.font = '10px Arial';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    
    gameState.obstacles.forEach((obstacle, index) => {
        const screenX = obstacle.x * gridSize - gameState.camera.x;
        const screenY = obstacle.y * gridSize - gameState.camera.y;
        
        // 检查是否在视口内
        if (screenX >= -gridSize && screenX <= gameConfig.viewportSize && 
            screenY >= -gridSize && screenY <= gameConfig.viewportSize) {
            
            // 绘制红色圆点标记
            ctx.beginPath();
            ctx.arc(screenX + gridSize/2, screenY + gridSize/2, 3, 0, Math.PI * 2);
            ctx.fill();
            
            // 显示坐标文本
            ctx.fillStyle = '#ff0000';
            ctx.fillText(`(${obstacle.x},${obstacle.y})`, screenX + gridSize/2, screenY - 10);
        }
    });
}

// 绘制障碍物碰撞标记
function drawObstacleCollisionMarkers(ctx) {
    const gridSize = gameConfig.gridSize;
    
    // 只在调试模式下显示
    if (!gameState.debugMode) return;
    
    // 绘制蛇头周围的碰撞检测区域
    if (gameState.snake.length > 0) {
        const head = gameState.snake[0];
        const screenX = head.x * gridSize - gameState.camera.x;
        const screenY = head.y * gridSize - gameState.camera.y;
        
        // 绘制蛇头碰撞检测区域（红色半透明矩形）
        ctx.fillStyle = 'rgba(255, 0, 0, 0.3)';
        ctx.fillRect(screenX, screenY, gridSize, gridSize);
        
        // 绘制蛇头位置标记
        ctx.strokeStyle = '#ffff00';
        ctx.lineWidth = 2;
        ctx.strokeRect(screenX, screenY, gridSize, gridSize);
        
        // 显示蛇头坐标
        ctx.fillStyle = '#ffff00';
        ctx.font = '12px Arial';
        ctx.textAlign = 'center';
        ctx.fillText(`蛇头(${head.x},${head.y})`, screenX + gridSize/2, screenY - 15);
        
        // 检查蛇头是否与障碍物碰撞
        const isColliding = gameState.obstacles.some(obstacle => 
            obstacle.x === head.x && obstacle.y === head.y
        );
        
        if (isColliding) {
            // 如果碰撞，绘制警告标记
            ctx.fillStyle = '#ff0000';
            ctx.font = 'bold 14px Arial';
            ctx.fillText('碰撞！', screenX + gridSize/2, screenY - 30);
        }
    }
    
    // 在障碍物位置绘制碰撞检测标记
    gameState.obstacles.forEach((obstacle, index) => {
        const screenX = obstacle.x * gridSize - gameState.camera.x;
        const screenY = obstacle.y * gridSize - gameState.camera.y;
        
        // 检查是否在视口内
        if (screenX >= -gridSize && screenX <= gameConfig.viewportSize && 
            screenY >= -gridSize && screenY <= gameConfig.viewportSize) {
            
            // 绘制障碍物碰撞检测区域（蓝色半透明矩形）
            ctx.fillStyle = 'rgba(0, 0, 255, 0.2)';
            ctx.fillRect(screenX, screenY, gridSize, gridSize);
            
            // 绘制障碍物边框
            ctx.strokeStyle = '#0000ff';
            ctx.lineWidth = 1;
            ctx.strokeRect(screenX, screenY, gridSize, gridSize);
        }
    });
}

// 保存最高分更新UI显示
function updateUI() {
    domElements.scoreValue.textContent = gameState.score;
    domElements.levelValue.textContent = gameState.level;
    domElements.snakeLengthValue.textContent = gameState.snakeLength;
    domElements.timeValue.textContent = formatTime(gameState.time);
    
    // 计算关卡进度
    const targetScore = gameState.level * 100; // 每关目标分数为关卡数×100
    const progress = Math.min((gameState.score / targetScore) * 100, 100);
    
    // 更新进度显示
    domElements.levelProgress.textContent = `${Math.floor(progress)}%`;
    domElements.progressFill.style.width = `${progress}%`;
    domElements.targetScore.textContent = targetScore;
}

// 格式化时间
function formatTime(seconds) {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}

// 开始计时器
function startTimer() {
    setInterval(() => {
        if (gameState.isRunning && gameState.gameLoop) {
            gameState.time++;
            updateUI();
        }
    }, 1000);
}

// 游戏结束
function gameOver() {
    gameState.isRunning = false;
    
    if (gameState.gameLoop) {
        clearInterval(gameState.gameLoop);
        gameState.gameLoop = null;
    }
    
    // 触发死亡特效
    triggerDeathEffect();
    
    // 游戏真正结束
    setTimeout(() => {
        showOverlay('游戏结束', `最终得分: ${gameState.score}\n游戏时间: ${formatTime(gameState.time)}`);
        
        // 保存最高分（可选）
        saveHighScore();
    }, 500); // 延迟显示，让特效先播放
}

// 触发死亡特效
function triggerDeathEffect() {
    gameState.deathEffect.active = true;
    gameState.deathEffect.startTime = Date.now();
    gameState.deathEffect.particles = [];
    
    // 创建粒子效果
    const snakeHead = gameState.snake[0];
    
    for (let i = 0; i < 20; i++) {
        gameState.deathEffect.particles.push({
            x: snakeHead.x * gameConfig.gridSize + gameConfig.gridSize / 2,
            y: snakeHead.y * gameConfig.gridSize + gameConfig.gridSize / 2,
            vx: (Math.random() - 0.5) * 10,
            vy: (Math.random() - 0.5) * 10,
            life: 1.0,
            color: i % 2 === 0 ? '#ff0000' : '#ff6b6b'
        });
    }
    
    // 开始特效动画
    animateDeathEffect();
}

// 动画死亡特效
function animateDeathEffect() {
    if (!gameState.deathEffect.active) return;
    
    const currentTime = Date.now();
    const elapsed = currentTime - gameState.deathEffect.startTime;
    const progress = Math.min(elapsed / gameState.deathEffect.duration, 1);
    
    // 更新粒子
    gameState.deathEffect.particles.forEach(particle => {
        particle.x += particle.vx;
        particle.y += particle.vy;
        particle.life = 1 - progress;
        particle.vx *= 0.98; // 减速
        particle.vy *= 0.98;
    });
    
    // 重绘画布
    drawGame();
    
    if (progress < 1) {
        requestAnimationFrame(animateDeathEffect);
    } else {
        gameState.deathEffect.active = false;
    }
}

// 绘制边界警告
function drawBoundaryWarning(ctx) {
    if (!gameState.boundaryWarning.active) return;
    
    const viewportSize = gameConfig.viewportSize;
    const intensity = gameState.boundaryWarning.intensity;
    const direction = gameState.boundaryWarning.direction;
    
    // 设置警告颜色（从黄色到红色渐变）
    const red = Math.floor(255 * intensity);
    const green = Math.floor(255 * (1 - intensity));
    const warningColor = `rgba(${red}, ${green}, 0, ${0.3 + intensity * 0.4})`;
    
    ctx.save();
    ctx.globalAlpha = 0.3 + intensity * 0.4;
    ctx.fillStyle = warningColor;
    
    // 根据方向绘制警告区域
    const warningSize = viewportSize * 0.1; // 警告区域大小
    
    switch (direction) {
        case 'left':
            ctx.fillRect(0, 0, warningSize, viewportSize);
            break;
        case 'right':
            ctx.fillRect(viewportSize - warningSize, 0, warningSize, viewportSize);
            break;
        case 'top':
            ctx.fillRect(0, 0, viewportSize, warningSize);
            break;
        case 'bottom':
            ctx.fillRect(0, viewportSize - warningSize, viewportSize, warningSize);
            break;
    }
    
    ctx.restore();
}

// 绘制小地图
function drawMiniMap() {
    const canvas = document.getElementById('miniMapCanvas');
    if (!canvas) return;
    
    const ctx = canvas.getContext('2d');
    const width = gameState.miniMap.width;
    const height = gameState.miniMap.height;
    
    // 清空画布
    ctx.clearRect(0, 0, width, height);
    
    // 绘制小地图背景
    ctx.fillStyle = '#1a1a2e';
    ctx.fillRect(0, 0, width, height);
    
    // 绘制网格
    ctx.strokeStyle = 'rgba(255, 255, 255, 0.1)';
    ctx.lineWidth = 0.5;
    const gridSize = 10; // 小地图网格大小
    for (let x = 0; x <= width; x += gridSize) {
        ctx.beginPath();
        ctx.moveTo(x, 0);
        ctx.lineTo(x, height);
        ctx.stroke();
    }
    for (let y = 0; y <= height; y += gridSize) {
        ctx.beginPath();
        ctx.moveTo(0, y);
        ctx.lineTo(width, y);
        ctx.stroke();
    }
    
    // 计算缩放比例
    const worldSize = gameConfig.worldSize / gameConfig.gridSize;
    const scaleX = width / worldSize;
    const scaleY = height / worldSize;
    
    // 绘制食物位置
    if (gameState.food) {
        const foodX = gameState.food.x * scaleX;
        const foodY = gameState.food.y * scaleY;
        
        // 绘制食物方向指示器（从蛇头指向食物）
        if (gameState.snake.length > 0) {
            const head = gameState.snake[0];
            const headX = head.x * scaleX;
            const headY = head.y * scaleY;
            
            // 计算方向向量
            const dx = foodX - headX;
            const dy = foodY - headY;
            const distance = Math.sqrt(dx * dx + dy * dy);
            
            if (distance > 5) { // 只在距离较远时显示方向指示
                const angle = Math.atan2(dy, dx);
                const indicatorLength = 8;
                const indicatorX = headX + Math.cos(angle) * indicatorLength;
                const indicatorY = headY + Math.sin(angle) * indicatorLength;
                
                ctx.strokeStyle = '#ff6b6b';
                ctx.lineWidth = 2;
                ctx.beginPath();
                ctx.moveTo(headX, headY);
                ctx.lineTo(indicatorX, indicatorY);
                ctx.stroke();
                
                // 绘制箭头
                ctx.fillStyle = '#ff6b6b';
                ctx.beginPath();
                ctx.moveTo(indicatorX, indicatorY);
                ctx.lineTo(indicatorX - 3, indicatorY - 2);
                ctx.lineTo(indicatorX - 3, indicatorY + 2);
                ctx.closePath();
                ctx.fill();
            }
        }
        
        // 绘制食物
        const foodType = gameConfig.foodTypes[gameState.currentFoodType];
        ctx.fillStyle = foodType.color;
        ctx.beginPath();
        ctx.arc(foodX, foodY, 3, 0, Math.PI * 2);
        ctx.fill();
        
        // 如果是高分食物，添加特殊效果
        if (gameState.currentFoodType === 'highScore') {
            ctx.strokeStyle = '#ffffff';
            ctx.lineWidth = 2;
            ctx.beginPath();
            ctx.arc(foodX, foodY, 5, 0, Math.PI * 2);
            ctx.stroke();
        }
    }
    
    // 绘制蛇身
    if (gameState.snake.length > 0) {
        // 绘制蛇身
        ctx.fillStyle = '#4CAF50';
        for (let i = 0; i < gameState.snake.length; i++) {
            const segment = gameState.snake[i];
            const x = segment.x * scaleX;
            const y = segment.y * scaleY;
            
            if (i === 0) {
                // 蛇头
                ctx.fillStyle = '#45a049';
                ctx.beginPath();
                ctx.arc(x, y, 4, 0, Math.PI * 2);
                ctx.fill();
            } else {
                // 蛇身
                ctx.fillStyle = '#4CAF50';
                ctx.fillRect(x - 2, y - 2, 4, 4);
            }
        }
    }
    
    // 绘制障碍物 - 使用障碍物渲染器
    if (window.obstacleRenderer && typeof window.obstacleRenderer.render === 'function') {
        window.obstacleRenderer.render(ctx, scaleX, scaleY);
    } else {
        // 备用渲染方式
        ctx.fillStyle = '#8B4513';
        gameState.obstacles.forEach(obstacle => {
            const x = obstacle.x * scaleX;
            const y = obstacle.y * scaleY;
            ctx.fillRect(x - 2, y - 2, 4, 4);
        });
    }
    
    // 绘制可视区域框
    const cameraX = gameState.camera.x / gameConfig.gridSize * scaleX;
    const cameraY = gameState.camera.y / gameConfig.gridSize * scaleY;
    const viewportWidth = gameConfig.viewportSize / gameConfig.gridSize * scaleX;
    const viewportHeight = gameConfig.viewportSize / gameConfig.gridSize * scaleY;
    
    ctx.strokeStyle = 'rgba(76, 175, 80, 0.8)';
    ctx.lineWidth = 2;
    ctx.strokeRect(cameraX, cameraY, viewportWidth, viewportHeight);
}

// 保存最高分
function saveHighScore() {
    const highScores = JSON.parse(localStorage.getItem('snakeHighScores') || '[]');
    highScores.push({
        score: gameState.score,
        level: gameState.level,
        time: gameState.time,
        difficulty: gameState.difficulty,
        date: new Date().toISOString()
    });
    
    // 只保留前10个最高分
    highScores.sort((a, b) => b.score - a.score);
    highScores.splice(10);
    
    localStorage.setItem('snakeHighScores', JSON.stringify(highScores));
}

// 显示覆盖层
function showOverlay(title, message) {
    domElements.overlayTitle.textContent = title;
    domElements.overlayMessage.textContent = message;
    
    // 移除可能存在的继续按钮
    const existingContinueBtn = document.getElementById('continueBtn');
    if (existingContinueBtn) {
        existingContinueBtn.remove();
    }
    
    domElements.gameOverlay.classList.remove('hidden');
}

// 隐藏覆盖层
function hideOverlay() {
    domElements.gameOverlay.classList.add('hidden');
}

// 加载地图文件
function loadMap(mapFilePath) {
    console.log('开始加载地图文件:', mapFilePath);
    
    // 处理相对路径，确保从正确的根目录加载
    let finalPath = mapFilePath;
    
    // 如果路径以../开头，说明是从pages目录调用的，需要修正路径
    if (mapFilePath.startsWith('../')) {
        finalPath = mapFilePath.substring(3); // 直接移除../前缀
    }
    
    console.log('最终地图文件路径:', finalPath);
    
    // 使用XMLHttpRequest代替fetch，避免CORS问题
    const xhr = new XMLHttpRequest();
    xhr.open('GET', finalPath, true);
    xhr.responseType = 'json';
    
    xhr.onload = function() {
        if (xhr.status === 200) {
            const mapData = xhr.response;
            console.log('地图文件加载成功，数据:', mapData);
            
            // 验证地图数据格式
            if (!mapData.mode || !mapData.width || !mapData.height || !mapData.gridSize) {
                throw new Error('地图数据格式不正确');
            }
            
            // 检查障碍物数据
            if (mapData.elements && mapData.elements.obstacles) {
                console.log(`地图包含 ${mapData.elements.obstacles.length} 个障碍物`);
            }
            
            // 应用地图配置
            applyMapConfig(mapData);
            
            // 显示加载成功消息
            showOverlay('地图加载成功', `已加载 ${mapData.mode} 模式地图 (${mapData.width}×${mapData.height})`);
            
            console.log('地图配置应用完成');
            
            // 3秒后自动隐藏消息
            setTimeout(() => {
                if (!gameState.isRunning) {
                    hideOverlay();
                }
            }, 3000);
        } else {
            throw new Error(`地图文件加载失败: ${xhr.status}`);
        }
    };
    
    xhr.onerror = function() {
        console.error('地图加载错误: 网络错误');
        showOverlay('地图加载失败', '网络错误，请检查文件路径');
    };
    
    xhr.send();
}

// 应用地图配置
function applyMapConfig(mapData) {
    console.log('开始应用地图配置...');
    
    // 保存当前地图数据
    gameState.currentMap = mapData;
    
    // 更新游戏配置 - 修复地图尺寸问题
    // 地图数据中的width和height是像素值，需要转换为网格数量
    const gridCountX = Math.floor(mapData.width / mapData.gridSize);
    const gridCountY = Math.floor(mapData.height / mapData.gridSize);
    
    // 更新游戏配置中的网格数量
    gameConfig.gridCountX = gridCountX;
    gameConfig.gridCountY = gridCountY;
    gameConfig.worldSize = mapData.width;  // 世界大小（像素）
    gameConfig.gridSize = mapData.gridSize; // 网格大小（像素）
    gameConfig.viewportSize = Math.min(mapData.width, 600); // 确保视口不超过画布大小
    
    // 重新设置画布大小
    domElements.canvas.width = gameConfig.viewportSize;
    domElements.canvas.height = gameConfig.viewportSize;
    console.log(`画布大小已更新为: ${gameConfig.viewportSize} × ${gameConfig.viewportSize}`);
    console.log(`地图网格数量: ${gridCountX} × ${gridCountY} 个网格`);
    
    // 启用调试模式
    gameState.debugMode = true;
    console.log('调试模式已启用');
    
    console.log(`地图配置: 世界大小=${mapData.width}px, 网格大小=${mapData.gridSize}px, 网格数量=${gridCountX}×${gridCountY}`);
    
    // 应用地图元素
    if (mapData.elements) {
        // 应用障碍物 - 修复障碍物渲染问题
        if (mapData.elements.obstacles) {
            // 将像素坐标转换为网格坐标，并过滤掉超出地图范围的障碍物
            gameState.obstacles = mapData.elements.obstacles.map(obs => {
                const gridX = Math.floor(obs.x / mapData.gridSize);
                const gridY = Math.floor(obs.y / mapData.gridSize);
                console.log(`转换障碍物坐标: 像素(${obs.x},${obs.y}) -> 网格(${gridX},${gridY})`);
                return { x: gridX, y: gridY };
            }).filter(obs => {
                // 过滤掉超出地图范围的障碍物
                const isValid = obs.x >= 0 && obs.x < gridCountX && obs.y >= 0 && obs.y < gridCountY;
                if (!isValid) {
                    console.warn(`障碍物坐标超出范围: (${obs.x}, ${obs.y})，将被过滤`);
                }
                return isValid;
            });
            
            console.log(`已加载 ${gameState.obstacles.length} 个有效障碍物`);
            console.log('障碍物位置(网格坐标):', gameState.obstacles.slice(0, 10));
            
            // 详细检查障碍物数据
            console.log('障碍物数据验证:');
            gameState.obstacles.forEach((obs, index) => {
                console.log(`障碍物 ${index}: x=${obs.x}, y=${obs.y}`);
            });
            
            // 重新初始化障碍物渲染器（使用新的游戏配置）
            const ctx = domElements.canvas.getContext('2d');
            if (window.obstacleRenderer && typeof window.obstacleRenderer.initialize === 'function') {
                window.obstacleRenderer.initialize(ctx, gameConfig);
                console.log('障碍物渲染器已重新初始化');
            }
            
            // 使用障碍物渲染器 - 确保传递正确的障碍物数据
            if (window.obstacleRenderer && typeof window.obstacleRenderer.setObstacles === 'function') {
                window.obstacleRenderer.setObstacles(gameState.obstacles);
                console.log('障碍物已传递给障碍物渲染器');
                
                // 验证障碍物渲染器状态
                console.log('障碍物渲染器状态验证:');
                console.log('- 初始化状态:', window.obstacleRenderer.initialized);
                console.log('- 障碍物数量:', window.obstacleRenderer.getObstacleCount ? window.obstacleRenderer.getObstacleCount() : 'N/A');
            }
        }
        
        // 如果有生成点，设置蛇的初始位置
        if (mapData.elements.spawnPoints && mapData.elements.spawnPoints.length > 0) {
            const spawnPoint = mapData.elements.spawnPoints[0];
            // 重置蛇的位置
            gameState.snake = [];
            for (let i = 0; i < gameState.snakeLength; i++) {
                gameState.snake.push({ x: spawnPoint.x - i, y: spawnPoint.y });
            }
            console.log('蛇初始位置已设置');
        }
    }
    
    // 重新初始化网格缓存
    initGridCache();
    
    // 重新生成食物（确保食物不会生成在障碍物上）
    generateFood();
    
    // 重新绘制游戏
    drawGame();
    
    console.log('地图配置应用完成');
}

// 重置地图（恢复到默认配置）
function resetMap() {
    // 重置游戏配置
    gameConfig.worldSize = 1200;
    gameConfig.gridSize = 20;
    gameConfig.gridCountX = 60;  // 重置网格数量X
    gameConfig.gridCountY = 60;  // 重置网格数量Y
    
    // 清空当前地图
    gameState.currentMap = null;
    gameState.obstacles = [];
    
    // 重新初始化网格缓存
    initGridCache();
    
    // 重置蛇的位置
    resetGame();
    
    // 显示重置消息
    showOverlay('地图已重置', '已恢复到默认游戏配置');
    
    // 3秒后自动隐藏消息
    setTimeout(() => {
        if (!gameState.isRunning) {
            hideOverlay();
        }
    }, 3000);
}